define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/order/index',
                    add_url: 'order/order/add',
                    edit_url: 'order/order/edit',
                    multi_url: 'order/order/multi',
                    del_url: 'order/order/del',
                    table: 'fa_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    // 添加城市和学校过滤参数
                    params.city_id = $('#c-cityarea_id').val();
                    params.school_id = $('#c-school_id').val();
                    return params;
                },
                escape: false,
                pk: 'id',
                sortName: 'weigh desc,id desc', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc") `refund_time``refund_amount``refund_status`
                columns: [
                    [
                        {
                            field: 'row_number',
                            title: '序号',
                            align: 'center',
                            formatter: function (value, row, index) {
                                var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;
                                var pageSize = $('#table').bootstrapTable('getOptions').pageSize;
                                return pageSize * (pageNumber - 1) + index + 1;
                            }
                        },
                        { checkbox: true },
                        { field: 'classes_id', title: '班级ID ', align: 'left' },
                        { field: 'classes_name', title: '课程名称' },
                        { field: 'user_id', title: '学员ID' },
                        { field: 'student_name', title: '学员名称' },
                        { field: 'mobile', title: '学员手机号' },
                        { field: 'registration_name', title: '报名姓名' },
                        { field: 'registration_phone', title: '报名手机号' },
                        { field: 'total_fee', title: '金额 ' },
                        { field: 'pay_channel', title: '支付状态' },
                        { field: 'pay_time', title: '支付时间' },
                        {
                            field: 'pay_channel_order_sn', title: '支付渠道单号',
                            formatter: function (value, row, index) {
                                var html = value;
                                // 如果订单已支付，显示退款按钮
                                if (row.pay_status == 1) {
                                    html += '<br><a href="javascript:;" class="btn btn-xs btn-danger btn-refund" data-id="' + row.id + '">退款</a>';
                                }
                                return html;
                            }
                        },
                        { field: 'refund_time', title: '退款时间' },
                        { field: 'refund_status', title: '退款状态' },
                        { field: 'refund_amount', title: '退款金额' },
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'detail',
                                //     classname: 'btn btn-xs btn-primary btn-click',
                                //     icon: 'fa fa-sitemap',
                                //     click: function (value, row, index) {
                                //         Backend.api.open('/adminht.php/dept/dept?relType=school&relId='+row.id+'&ref=addtabs', '组织结构2', {
                                //             max: true,
                                //             area: ['80%', '80%'],
                                //             //offset: ['0px', '0px'],
                                //             callback: function (data) {
                                //                 Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //             }
                                //         });
                                //     }
                                // }
                            ]
                        }
                    ]
                ]
            });
            $(document).on('fa.event.success', function (event, data) {
                setTimeout(function () {
                    location.reload();
                }, 1000);
            });

            // 引入通用的城市学校过滤脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 绑定退款按钮点击事件
            $(document).on('click', '.btn-refund', function () {
                var orderId = $(this).data('id');
                Layer.confirm('请选择退款操作方式', {
                    title: '退款确认',
                    btn: ['显示退款二维码', '直接退款', '取消'],
                    btn3: function (index, layero) {
                        Layer.close(index);
                    }
                }, function (index) {
                    // 按钮1：显示退款二维码
                    Layer.close(index);
                    var loadingIndex = Layer.load(2, { shade: [0.3, '#fff'] });

                    $.ajax({
                        url: 'order/order/getRefundQrcode',
                        type: 'POST',
                        data: { id: orderId },
                        success: function (res) {
                            Layer.close(loadingIndex);
                            if (typeof res === 'string') {
                                try {
                                    res = JSON.parse(res);
                                } catch (e) {
                                    console.error("JSON parse error", e);
                                }
                            }
                            if (res.code === 1) {
                                Layer.open({
                                    type: 1,
                                    title: '请扫描下方二维码进行退款',
                                    closeBtn: 1,
                                    area: ['300px', '350px'],
                                    shadeClose: true,
                                    content: '<div style="text-align:center;padding:20px;"><img src="data:image/png;base64,' + res.data + '" style="width:200px;height:200px;"/><br><p style="margin-top:10px;">请使用微信扫码进入小程序退款</p></div>'
                                });
                            } else {
                                Layer.msg(res.msg || '获取二维码失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            Layer.close(loadingIndex);
                            Layer.msg('请求失败', { icon: 2 });
                        }
                    });
                }, function (index) {
                    // 按钮2：直接退款
                    Layer.close(index);
                    Layer.confirm('确定要直接退款此订单吗？<br><span class="text-danger">注意：这将直接调用微信支付接口退款，资金将原路返回！</span>', {
                        title: '确认直接退款',
                        icon: 3
                    }, function (innerIndex) {
                        Layer.close(innerIndex);
                        var loadingIndex = Layer.load(2, { shade: [0.3, '#fff'] });

                        $.ajax({
                            url: 'order/order/refund',
                            type: 'POST',
                            data: { id: orderId },
                            success: function (res) {
                                Layer.close(loadingIndex);
                                if (typeof res === 'string') {
                                    try {
                                        res = JSON.parse(res);
                                    } catch (e) {
                                        console.error("JSON parse error", e);
                                    }
                                }
                                if (res.code === 1) {
                                    Layer.msg(res.msg || '退款成功', { icon: 1 });
                                    table.bootstrapTable('refresh');
                                } else {
                                    Layer.msg(res.msg || '退款失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                Layer.close(loadingIndex);
                                Layer.msg('退款请求失败', { icon: 2 });
                            }
                        });
                    });
                });
            });
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);

            Controller.api.bindevent();
        },
        edit: function () {
            var row = JSON.parse($('#row').val());
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    return Controller;
});